package yxy.game.pm2.command.soul;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Hero;
import yxy.game.pm2.bean.Soul;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.HeroMessage;
import yxy.game.pm2.module.hero.HeroHandle;
import yxy.game.pm2.module.hero.SoulHandle;

/** 魂玉 魂玉重铸保存 */
@MessageType(proto = Command.SoulRecoinSave, classtype = HeroMessage.SoulRecoinSaveRequest.class)
public class CMD_SoulRecoinSave extends Command<HeroMessage.SoulRecoinSaveRequest> {

	@Override
	public void execute(MessageSource messageSource, HeroMessage.SoulRecoinSaveRequest request) {
		String playerCode = messageSource.getTag();
		String soulCode = request.getCode();

		HeroMessage.SoulRecoinSaveResponse.Builder response = HeroMessage.SoulRecoinSaveResponse.newBuilder();

		try {
			if (Hero.lockHero(playerCode) && Soul.lockSoul(playerCode)) {

				Soul soul = Soul.get(playerCode, soulCode);
				if (soul == null) {
					send(messageSource, response, Result.ParamError);
					return;
				}
				if (soul.getRePropertyIds() != null) {
					soul.setPropertyIds(soul.getRePropertyIds());
					soul.setRePropertyIds(null);
				}
				if (soul.getReSkillIds() != null) {
					soul.setSkillIds(soul.getReSkillIds());
					soul.setReSkillIds(null);
				}
				Soul.set(playerCode, soul);

				// 检查战力
				if (soul.getHero() != null) {
					Hero hero = Hero.get(playerCode, soul.getHero());
					if (hero != null) {
						new HeroHandle().updateHero(playerCode, hero);
					}
				}

				response.setSoul(new SoulHandle().packSoul(soul));
				send(messageSource, response, Result.Success);

			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			Hero.unlockHero(playerCode);
			Soul.unlockSoul(playerCode);
		}
	}

	private void send(MessageSource messageSource, HeroMessage.SoulRecoinSaveResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}